﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace MusicAcademy
{
    public partial class frmRegisterTerm : Form
    {
        public frmRegisterTerm()
        {
            InitializeComponent();
        }

        public int StudentID = -1;
        public int TermID = -1;
        int TeacherID = -1;
        int recordID = -1;
        int cost;
        int teacherPercent;

        private void RefreshGrid()
        {
            fullRegisterTableAdapter.Fill(musicAcademyDataSet.FullRegister, "", "", "");
        }

        private bool isValid()
        {
            bool valid = true;
            if (StudentID==-1)
                valid = Globals.SetError(txtStudent);
            else
                Globals.SetValid(txtStudent);

            if (TermID == -1)
                valid = Globals.SetError(txtTerm);
            else
                Globals.SetValid(txtTerm);

            return valid;
        }
        private void frmRegisterTerm_Load(object sender, EventArgs e)
        {
            if (UserManager.HasAccess(this.Name, "View") == false)
            {
                MessageBox.Show("شما اجازه ی دیدن این فرم را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.Close();
            }
            RefreshGrid();
            grdRegister.ClearSelection();
        }

        private void btnSelectStudent_Click(object sender, EventArgs e)
        {
            ListOfPersons p = new ListOfPersons();
            p.PersonType = 2;
            if (p.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                StudentID = p.SelectedID;
                txtStudent.Text = p.FirstName + " " + p.LastName;
            }
        }

        private void btnSelectTerm_Click(object sender, EventArgs e)
        {
            ListOfTerms t = new ListOfTerms();
            if (t.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                TermID = t.SelectedID;
                txtTerm.Text = t.ToolName + " - استاد " + t.TeacherName;

                LoadTerm();
            }
        }

        private void LoadTerm()
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();
            SqlDataReader dreader;
            string s = "";

            com.Connection = con;
            com.CommandType = CommandType.Text;

            com.CommandText = "SELECT TermProgram.time, WeekDays.dayName, classNumber FROM TermProgram INNER JOIN WeekDays ON TermProgram.DOW = WeekDays.ID INNER JOIN Class ON TermProgram.classID=Class.ID WHERE termID=@termID";
            com.Parameters.AddWithValue("@termID", TermID);

            con.Open();
            dreader = com.ExecuteReader();
            while (dreader.Read())
            {
                s += (s == "" ? "" : "  --  ") + dreader["dayName"].ToString() + " (" + dreader["time"].ToString() + ") ک: " + dreader["classNumber"].ToString();
            }
            dreader.Close();
            com.Parameters.Clear();

            com.CommandText = "SELECT Term.* FROM Term WHERE Term.ID=@ID";
            com.Parameters.AddWithValue("@ID", TermID);

            dreader = com.ExecuteReader();
            dreader.Read();

            if (dreader["isGroup"].ToString() == "0")
            {
                grpSingle.Visible = true;
                grpGroup.Visible = false;
                lblCost1.Text = dreader["cost"].ToString();
                lblDays1.Text = dreader["days"].ToString();
                lblTeachingTime1.Text = dreader["teachingTime"].ToString();
                lblWeeklyProgram1.Text = s;
                TeacherID = Convert.ToInt32(dreader["teacherID"]);
                cost = int.Parse(lblCost1.Text);
                teacherPercent = Convert.ToInt32(dreader["teacherPercent"]);
            }
            else
            {
                grpSingle.Visible = false;
                grpGroup.Visible = true;
                lblCost2.Text = dreader["cost"].ToString();
                lblDays2.Text = dreader["days"].ToString();
                lblStartDate2.Text = dreader["startDate"].ToString();
                lblWeeklyProgram2.Text = s;
                TeacherID = Convert.ToInt32(dreader["teacherID"]);
                cost = int.Parse(lblCost2.Text);
                teacherPercent = Convert.ToInt32(dreader["teacherPercent"]);
            }
            dreader.Close();
            com.Parameters.Clear();

            con.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (UserManager.HasAccess(this.Name, "Insert") == false)
                {
                    MessageBox.Show("شما اجازه ی اضافه کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            if (isValid() == false)
                return;
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();
            SqlDataReader dreader;
            com.Connection = con;
            com.CommandType = CommandType.Text;
            com.CommandText = "INSERT INTO Register (registerDate, studentID, termID, academyID, creator, createDate) VALUES (@registerDate, @studentID, @termID, @academyID, @creator, @createDate); SELECT TOP 1 ID FROM Register ORDER BY ID DESC";
            com.Parameters.AddWithValue("@registerDate", Globals.Get10CharDate());
            com.Parameters.AddWithValue("@studentID", StudentID);
            com.Parameters.AddWithValue("@termID", TermID);
            com.Parameters.AddWithValue("@academyID", Program.academyID);
            com.Parameters.AddWithValue("@creator", Program.userID);
            com.Parameters.AddWithValue("@createDate", Globals.Get10CharDate());

            con.Open();
            dreader = com.ExecuteReader();
            dreader.Read();
            recordID = Convert.ToInt32(dreader["ID"]);
            dreader.Close();
            con.Close();

            Globals.SaveTransaction(StudentID, Globals.Get10CharDate(), 0, cost, "شهریه کلاس " + txtTerm.Text);
            Globals.SaveTransaction(TeacherID, Globals.Get10CharDate(), (int)(teacherPercent * cost / 100.0), 0, "حق التدریس کلاس " + txtTerm.Text.Substring(0, txtTerm.Text.IndexOf("-")) + " هنرجو " + txtStudent.Text);
            Globals.SaveTransaction(-1, Globals.Get10CharDate(), (int)((100 - teacherPercent) * cost / 100.0), 0, "شهریه کلاس " + txtTerm.Text + " هنرجو " + txtStudent.Text);

            RefreshGrid();

            MessageBox.Show("ذخیره شد", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            AutoMakeSessions();

            btnSave.Enabled = false;
            btnDelete.Enabled = true;
            btnPayment.Enabled = true;
            btnSessions.Enabled = true;

        }

        private void AutoMakeSessions()
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();
            SqlDataReader dreader;
            List<int> DOW = new List<int>();
            List<string> Time = new List<string>();
            List<int> ClassID = new List<int>();
            int days, isGroup, teachingTime;
            int i = 0, j;
            DateTime d;
            int curDOW;
            string[] s;
            string startDate;

            com.Connection = con;
            com.CommandType = CommandType.Text;

            com.CommandText = "SELECT ID FROM Session WHERE registerID=@registerID";
            com.Parameters.AddWithValue("@registerID", recordID);

            con.Open();
            dreader = com.ExecuteReader();
            if (dreader.HasRows)
            {
                dreader.Close();
                con.Close();
                MessageBox.Show("برنامه ریزی جلسات این کلاس قبلا انجام شده است", "خطا", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            dreader.Close();
            com.Parameters.Clear();

            com.CommandText = "SELECT * FROM TermProgram WHERE termID=@termID ORDER BY DOW; SELECT * FROM Term WHERE ID=@termID";
            com.Parameters.AddWithValue("@termID", TermID);

            dreader = com.ExecuteReader();
            while (dreader.Read())
            {
                DOW.Add(Convert.ToInt32(dreader["DOW"]));
                Time.Add(dreader["time"].ToString());
                ClassID.Add(Convert.ToInt32(dreader["classID"]));
            }

            dreader.NextResult();
            dreader.Read();
            days = Convert.ToInt32(dreader["days"]);
            isGroup = Convert.ToInt32(dreader["isGroup"]);
            teachingTime = Convert.ToInt32(dreader["teachingTime"]);
            startDate = dreader["startDate"].ToString();

            dreader.Close();
            com.Parameters.Clear();

            if (isGroup == 0)
            {
                if (string.Compare(startDate, Globals.Get10CharDate()) <= 0)
                    d = DateTime.Now;
                else
                    d = Globals.GregorianDate(startDate);

                curDOW = Globals.GetDOW(d.DayOfWeek);
            }
            else
            {
                d = Globals.GregorianDate(startDate);
                curDOW = Globals.GetDOW(d.DayOfWeek);
            }

            for (i = 0; i < DOW.Count; i++)
            {
                if (DOW[i] == curDOW)
                    break;
            }
            if (i == DOW.Count)
            {
                i = 0;
                if (curDOW < DOW[i])
                    d.AddDays(DOW[i] - curDOW);
                else
                    d = d.AddDays(7 - (curDOW - DOW[i]));
                curDOW=DOW[i];
            }

            for (j = 0; j < days; j++)
            {
                if (isGroup == 0)
                {
                    if (curDOW == DOW[i])
                    {
                        if (j > 0)
                            d = d.AddDays(7);
                    }
                    else if (curDOW < DOW[i])
                    {
                        d = d.AddDays(DOW[i] - curDOW);
                        curDOW = DOW[i];
                    }
                    else
                    {
                        d = d.AddDays(7 - (curDOW - DOW[i]));
                        curDOW = DOW[i];
                    }

                    d = d.AddSeconds(-d.Second).AddMinutes(-d.Minute).AddHours(-d.Hour);

                    com.CommandText = "SELECT MAX(time) AS T FROM Session INNER JOIN Register ON Register.ID=Session.registerID WHERE termID=@termID AND date=@date";
                    com.Parameters.AddWithValue("@termID", TermID);
                    com.Parameters.AddWithValue("@date", Globals.Get10CharDate(d));
                    dreader = com.ExecuteReader();
                    if (dreader.Read() && dreader["T"] != DBNull.Value)
                    {
                        s = dreader["T"].ToString().Split(':');
                        d = d.AddHours(int.Parse(s[0])).AddMinutes(int.Parse(s[1]));
                    }
                    else
                    {
                        s = Time[i].Split(':');
                        d = d.AddHours(int.Parse(s[0])).AddMinutes(int.Parse(s[1]));
                    }
                    d = d.AddMinutes(teachingTime);
                    dreader.Close();
                    com.Parameters.Clear();
                }
                else
                {
                    if (curDOW == DOW[i])
                    {
                        if (j > 0)
                            d = d.AddDays(7);
                    }
                    else if (curDOW < DOW[i])
                    {
                        d = d.AddDays(DOW[i] - curDOW);
                        curDOW = DOW[i];
                    }
                    else
                    {
                        d = d.AddDays(7 - (curDOW - DOW[i]));
                        curDOW = DOW[i];
                    }
                    
                    d = d.AddSeconds(-d.Second).AddMinutes(-d.Minute).AddHours(-d.Hour);

                    s = Time[i].Split(':');
                    d = d.AddHours(int.Parse(s[0])).AddMinutes(int.Parse(s[1]));
                }

                com.CommandText = "SELECT ID FROM Holiday WHERE academyID=@academyID AND date=@date";
                com.Parameters.AddWithValue("@academyID", Program.academyID);
                com.Parameters.AddWithValue("@date", Globals.Get10CharDate(d));
                dreader = com.ExecuteReader();
                if (dreader.HasRows)
                {
                    j--;
                    i = (i + 1) % DOW.Count;
                    dreader.Close();
                    com.Parameters.Clear();
                    continue;
                }
                dreader.Close();
                com.Parameters.Clear();

                com.CommandText = "INSERT INTO Session (date, time, status, classID, registerID, grade, academyID, creator, createDate) VALUES (@date, @time, @status, @classID, @registerID, @grade, @academyID, @creator, @createDate)";
                com.Parameters.AddWithValue("@date", Globals.Get10CharDate(d));
                com.Parameters.AddWithValue("@time", d.Hour.ToString("00") + ":" + d.Minute.ToString("00"));
                com.Parameters.AddWithValue("@status", 0);
                com.Parameters.AddWithValue("@classID", ClassID[i]);
                com.Parameters.AddWithValue("@registerID", recordID);
                com.Parameters.AddWithValue("@grade", 0);
                com.Parameters.AddWithValue("@academyID", Program.academyID);
                com.Parameters.AddWithValue("@creator", Program.userID);
                com.Parameters.AddWithValue("@createDate", Globals.Get10CharDate());
                com.ExecuteNonQuery();
                com.Parameters.Clear();

                i = (i + 1) % DOW.Count;
            }

            com.Parameters.Clear();

            com.CommandText = "UPDATE Session SET status=5 WHERE registerID=@registerID AND (date<@date OR (date=@date AND time<@time))";
            com.Parameters.AddWithValue("@registerID", recordID);
            com.Parameters.AddWithValue("@date", Globals.Get10CharDate());
            com.Parameters.AddWithValue("@time", DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00"));
            com.ExecuteNonQuery();

            MessageBox.Show("برنامه ریزی جلسات انجام شد .", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            con.Close();
        }

        private void grdRegister_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;

            Globals.SetValid(txtStudent);
            Globals.SetValid(txtTerm);

            recordID = Convert.ToInt32(grdRegister.Rows[e.RowIndex].Cells["ID"].Value);
            txtTerm.Text = grdRegister.Rows[e.RowIndex].Cells["toolName"].Value.ToString() + " - استاد " + grdRegister.Rows[e.RowIndex].Cells["teacherName"].Value.ToString();
            TermID = Convert.ToInt32(grdRegister.Rows[e.RowIndex].Cells["_termID"].Value);
            txtStudent.Text = grdRegister.Rows[e.RowIndex].Cells["studentName"].Value.ToString();
            StudentID = Convert.ToInt32(grdRegister.Rows[e.RowIndex].Cells["_studentID"].Value);
            LoadTerm();
            btnSave.Enabled = false;
            btnDelete.Enabled = true;
            btnSelectStudent.Enabled = false;
            btnSelectTerm.Enabled = false;
            btnNewStudent.Enabled = false;
            btnPayment.Enabled = true;
            btnSessions.Enabled = true;
        }


        private void ClearForm()
        {
            btnDelete.Enabled = false;
            btnSessions.Enabled = false;
            btnPayment.Enabled = false;
            btnSelectStudent.Enabled = true;
            btnSelectTerm.Enabled = true;
            btnNewStudent.Enabled = true;
            btnSave.Enabled = true;

            grpGroup.Visible = false;
            grpSingle.Visible = false;
            txtStudent.Text = "";
            txtTerm.Text = "";
            TermID = -1;
            StudentID = -1;
            recordID = -1;

            Globals.SetValid(txtStudent);
            Globals.SetValid(txtTerm);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        private void btnPayment_Click(object sender, EventArgs e)
        {
            frmNewPayment p = new frmNewPayment();
            p.StudentID = StudentID;
            p.PaymentType = 1;//Credit
            p.PersonType = 2;
            p.Text = "پرداخت شهریه";
            p.lblName.Text = "هنرجو :";
            p.txtStudent.Text = txtStudent.Text;
            if (grpGroup.Visible == true)
                p.txtAmount.Text = lblCost2.Text;
            else
                p.txtAmount.Text = lblCost1.Text;
            p.txtDescription.Text = "شهریه کلاس " + txtTerm.Text;
            p.ShowDialog();
        }

        private void btnSessions_Click(object sender, EventArgs e)
        {
            frmSessions s = new frmSessions();
            s.RegisterID = recordID;
            s.txtRegister.Text = txtStudent.Text + " در کلاس " + txtTerm.Text;
            s.ShowDialog();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (UserManager.HasAccess(this.Name, "Delete") == false)
            {
                MessageBox.Show("شما اجازه ی حذف کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (MessageBox.Show("آیا از حذف این رکورد اطمینان دارید ؟", "حذف", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
                SqlCommand com = new SqlCommand();
                com.Connection = con;
                com.CommandType = CommandType.Text;
                com.CommandText = "DELETE FROM Session WHERE registerID=@registerID; DELETE FROM Register WHERE ID=@registerID";
                com.Parameters.AddWithValue("@registerID", recordID);
                con.Open();
                com.ExecuteNonQuery();
                con.Close();

                ClearForm();
                RefreshGrid();
                MessageBox.Show("حذف شد", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void btnNewStudent_Click(object sender, EventArgs e)
        {
            frmStudents s = new frmStudents();
            s.ShowDialog();
        }

    }
}
